package com.yuanxiao.client;

import com.yuanxiao.coder.JSONSerializer;
import com.yuanxiao.coder.RpcDecoder;
import com.yuanxiao.coder.RpcEncoder;
import com.yuanxiao.globalid.IdWorler;
import com.yuanxiao.model.RpcRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RpcConsumer {
    //创建线程池对象
    private static ExecutorService executor =
            Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private static UserClientHandler userClientHandler ;
    //创建代理对象  providerName : UserService#sayHello
    public Object createProxy(final Class<?> serviceClass){
        //借助动态代理生成代理对象
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serviceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //调用 创建netty客户端 的方法
                if(userClientHandler==null){
                    initClinet();
                }
                //??这里为啥会有tostring?
                if(method.getName().equals("toString")) {
                    // 其他方法不做处理，免得发出不受控制的请求
                    return "";
                }



                //设置参数
              //  userClientHandler.setPara(providerName+args[0]);
                RpcRequest rpcRequest = new RpcRequest();
                rpcRequest.setRequestId(String.valueOf(new IdWorler(21,31,0).nextId()));
                rpcRequest.setClassName(serviceClass.getName());
                rpcRequest.setMethodName(method.getName());
                rpcRequest.setParameterTypes(method.getParameterTypes());
                rpcRequest.setParameters(args);
                userClientHandler.setPara(rpcRequest);
                //真正的去服务端请求数据
                Object o = executor.submit(userClientHandler).get();
                System.out.println("返回结果是："+o);
                return o;
            }
        });
    }

    //创建netty客户端
    public static void initClinet() throws InterruptedException {
        userClientHandler=new UserClientHandler();
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        JSONSerializer jsonSerializer = new JSONSerializer();
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(new RpcEncoder(RpcRequest.class,jsonSerializer));
                        //pipeline.addLast(new RpcDecoder(RpcRequest.class,jsonSerializer));
                        pipeline.addLast(userClientHandler);
                    }
                });
        bootstrap.connect("127.0.0.1",8990).sync();

    }

}
